import {
  Controller,
  Get,
  Inject,
  Query,
  Post,
  Body,
  Config,
} from '@midwayjs/core';
import { WechatService } from '../service/wechat.service';
import { UserService } from '../service/user.service';
import { Context } from '@midwayjs/koa';

@Controller('/api/wechat')
export class WechatController {
  @Inject()
  ctx: Context;

  @Inject()
  wechatService: WechatService;

  @Inject()
  userService: UserService;

  @Config('wechat')
  wechatConfig;

  /**
   * 生成微信授权URL
   */
  @Get('/auth/url')
  async getWechatAuthUrl() {
    const { appid, redirectHost } = this.wechatConfig;
    // 注意：这里的 redirect_uri 必须经过 URL Encode，并且与公众号后台配置的网页授权域名一致
    const redirectUri = encodeURIComponent(
      `${redirectHost}/api/wechat/callback`
    );
    const scope = 'snsapi_userinfo';
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
    return { url };
  }

  @Get('/auth')
  async redirectToWechatAuth() {
    const { appid, redirectHost } = this.wechatConfig;
    // 从配置读取回调域名，更灵活
    const redirectUri = encodeURIComponent(
      `${redirectHost}/api/wechat/callback`
    );
    const scope = 'snsapi_userinfo';
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
    console.log('微信授权 URL:', url);
    this.ctx.redirect(url);
  }

  @Get('/callback')
  async handleWechatCallback(@Query('code') code: string) {
    if (!code) {
      this.ctx.body = '<h1>用户禁止授权</h1>';
      return;
    }

    try {
      // 1. 用 code 换取 access_token 和 openid
      const tokenData = await this.wechatService.getAccessToken(code);

      // 2. 用 access_token 和 openid 获取用户详细信息
      const userInfo = await this.wechatService.getUserInfo(
        tokenData.access_token,
        tokenData.openid
      );

      // 3. 根据 openid 查找或创建用户
      const user = await this.userService.findOrCreateUserByWechat(userInfo);

      // 4. 在这里，你可以生成一个 JWT token，并将其作为参数重定向回前端
      // 为了简化，我们暂时只重定向到前端首页
      // const token = generateJwtToken(user);
      // this.ctx.redirect(`http://your-frontend-url.com?token=${token}`);

      const token = 'wechat_token_' + user.id + '_' + Date.now();

      // 构建前端回调 URL（带用户信息）
      const frontendUrl = `${
        this.wechatConfig.redirectHost
      }?token=${encodeURIComponent(token)}&id=${encodeURIComponent(
        String(user.id)
      )}&isVip=${user.isVip ? 'true' : 'false'}&nickname=${encodeURIComponent(
        user.nickname || ''
      )}&avatar=${encodeURIComponent(user.avatar || '')}`;

      this.ctx.redirect(frontendUrl);

      console.log('User login/register success:', user);
    } catch (error) {
      console.error('Wechat callback error:', error);
      this.ctx.status = 500;
      this.ctx.body = `<h1>授权失败: ${error.message}</h1>`;
    }
  }

  @Post('/jssdk-config')
  async getJsSdkConfig(@Body('url') url: string) {
    if (!url) {
      this.ctx.status = 400;
      return { success: false, message: '缺少 url 参数' };
    }
    try {
      const config = await this.wechatService.createJsSdkSignature(url);
      return { success: true, data: config };
    } catch (error) {
      this.ctx.status = 500;
      return { success: false, message: error.message };
    }
  }

  @Post('/create-order')
  async createOrder(@Body('openid') openid: string) {
    if (!openid) {
      this.ctx.status = 400;
      return { success: false, message: '缺少 openid 参数' };
    }
    try {
      const totalFee = 1;
      const body = '测试商品';
      const tradeNo = `TEST_${Date.now()}`;
      const payParams = await this.wechatService.createUnifiedOrder(
        openid,
        totalFee,
        body,
        tradeNo
      );
      return { success: true, data: payParams };
    } catch (error) {
      this.ctx.status = 500;
      return { success: false, message: error.message };
    }
  }
}
